package es.wandererteam.tapakitty;

import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.AutoParallaxBackground;
import org.andengine.entity.scene.background.ParallaxBackground.ParallaxEntity;
import org.andengine.entity.scene.menu.MenuScene;
import org.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener;
import org.andengine.entity.scene.menu.item.IMenuItem;
import org.andengine.entity.scene.menu.item.SpriteMenuItem;
import org.andengine.entity.scene.menu.item.decorator.ScaleMenuItemDecorator;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.sprite.TiledSprite;
import org.andengine.entity.text.Text;
import org.andengine.input.touch.TouchEvent;
import org.andengine.input.touch.detector.ClickDetector;
import org.andengine.input.touch.detector.ClickDetector.IClickDetectorListener;
import org.andengine.input.touch.detector.ContinuousHoldDetector;
import org.andengine.input.touch.detector.HoldDetector;
import org.andengine.input.touch.detector.HoldDetector.IHoldDetectorListener;
import org.andengine.input.touch.detector.ScrollDetector;
import org.andengine.input.touch.detector.ScrollDetector.IScrollDetectorListener;
import org.andengine.input.touch.detector.SurfaceScrollDetector;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.util.color.Color;

import android.util.Log;
import android.widget.Toast;
import es.wandererteam.tapakitty.bussines.GameStatus;
import es.wandererteam.tapakitty.management.BaseScene;
import es.wandererteam.tapakitty.management.ResourcesManager;
import es.wandererteam.tapakitty.management.SceneManager;
import es.wandererteam.tapakitty.management.SceneManager.SceneType;

public class ShopScene extends BaseScene implements IOnMenuItemClickListener,
		IScrollDetectorListener, IOnSceneTouchListener, IClickDetectorListener,
		IHoldDetectorListener {
	// ===========================================================
	// Constants
	// ===========================================================
	protected static int CAMERA_WIDTH = 480;
	protected static int CAMERA_HEIGHT = 320;
	protected static int FONT_SIZE = 24;
	protected static int PADDING = 0;
	protected static int MENUITEMS = 5;
	protected static String[] ItemsName = { "Ribbon: +1", "Bell: +2",
			"Farm: +5", "Hell: +10", "Heaven: +50" };

	// ===========================================================
	// Fields
	// ===========================================================
private Color spriteColor;
	private long touchStarted = 0;
	private long touchEnded = 0;
	private long subTouch = 0;

	private static Text[] spritesNumItems;
	private static Text[] spritesPriceItems;
	private static Text spritesDescriptionItems;

	private ContinuousHoldDetector continuousHoldDetector;

	// Scrolling
	private SurfaceScrollDetector mScrollDetector;
	private ClickDetector mClickDetector;

	private float scrollMinY = 0;
	private float scrollMaxY;
	private float scrollCurrentY = 0;
	private int iItemClicked = -1;

	Sprite popup;

	
	protected TiledSprite spriteTexture;
	ITextureRegion iconTextureRegion;
	
	private Sprite spriteEncabezado;
	private Rectangle scrollBar;

	@Override
	public void createScene() {

		// Fill variables
		CAMERA_WIDTH = resourcesManager.getInstance().SCREEN_WIDTH;
		CAMERA_HEIGHT = resourcesManager.getInstance().SCREEN_HEIGHT;

		this.camera.set(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);

		createBackground();
		// createMenuChildScene();
		
	

		mScrollDetector = new SurfaceScrollDetector(this);
		mClickDetector = new ClickDetector(this);

		setOnSceneTouchListener(this);
		setTouchAreaBindingOnActionDownEnabled(true);
		setTouchAreaBindingOnActionMoveEnabled(true);
		setOnSceneTouchListenerBindingOnActionDownEnabled(true);
		
		
	
		
		
		CreateMenuBoxes();

		// registrando toque largo
		continuousHoldDetector = new ContinuousHoldDetector(this);
		this.registerUpdateHandler(continuousHoldDetector);

		// resourcesManager.loadMenuAudio();
		// loadSounds();
		createEncabezado();
		
	}

	public void loadSounds() {
	}

	@Override
	public void onBackKeyPressed() {
		SceneManager.getInstance().loadGameScene(engine);
	}

	@Override
	public SceneType getSceneType() {
		return SceneType.SCENE_MENU;
	}

	@Override
	public void disposeScene() {
		// TODO Auto-generated method stub
	}

	private void CreateMenuBoxes() {
		int spriteX = 0;
		int spriteY = 120;

		// Create sprites for numbers of objects
		spritesNumItems = new Text[MENUITEMS];
		// Create prices for the sprites
		spritesPriceItems = new Text[MENUITEMS];

		// current item counter
		int iItem = 1;
		

		 iconTextureRegion = resourcesManager.iconsTiledTextureRegion.getTextureRegion(1);
		for (int x = 0; x < MENUITEMS; x++) {
			// On Touch, save the clicked item in case it's a click and not a
			// scroll.
			final int itemToLoad = iItem;
			
	
			Sprite sprite = new Sprite(spriteX, spriteY,
					resourcesManager.iconsTiledTextureRegion.getTextureRegion(x), vbom) {
				public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
						final float pTouchAreaLocalX,
						final float pTouchAreaLocalY) {
					iItemClicked = itemToLoad;
					
					/////////////////////////////
					
					if (pSceneTouchEvent.isActionDown()) {
						touchStarted = System.currentTimeMillis();
					
			
						this.setColor(180f / 255f, 180f / 255f, 180f / 255f);
						
					}
					if (pSceneTouchEvent.isActionUp()) {
						this.setColor(1f, 1f, 1f);
						
						
						
						touchEnded = System.currentTimeMillis();
						
						subTouch = touchStarted - touchEnded;

						if (subTouch > -200) {
							// apretado corto

							subTouch = 0;
						} else {// apretado largo
							
							//popup();
							 
							subTouch = 0;
						}

					}
					//////////////////////			
					
					return false;
				}
			};
			
			//spriteX = (int) (CAMERA_WIDTH / 4 - sprite.getWidth() / 2);
			sprite.setX(0);
			
			iItem++;
			this.attachChild(sprite);
			this.registerTouchArea(sprite);

			// assigns sprites for numbers of objects
			spritesNumItems[x] = new Text(spriteX, spriteY,
					resourcesManager.itemsNumberFont, "0123456789", 10,
					resourcesManager.vbom);
			spritesNumItems[x].setText(String.valueOf(GameStatus.ITEMS[x]));
			spritesNumItems[x].setWidth((float) (sprite.getWidth() * 0.9));
			spritesNumItems[x].setHeight((float) (sprite.getHeight() * 0.2));
			spritesNumItems[x].setX(spriteX + sprite.getWidth() - spritesNumItems[x].getWidth());
			attachChild(spritesNumItems[x]);

			// assigns prices to the objects
			spritesPriceItems[x] = new Text(spriteX, spriteY,
					resourcesManager.itemsNumberFont, "0123456789", 10,
					resourcesManager.vbom);
			spritesPriceItems[x].setText(String
					.valueOf(GameStatus.ITEMS_PRICE[x]));
			spritesPriceItems[x].setX(spriteX + sprite.getWidth()
					- sprite.getWidth() / 2);
			spritesPriceItems[x].setY(spritesNumItems[x].getY()
					+ sprite.getHeight() / 6);
			attachChild(spritesPriceItems[x]);

			spriteY += 0 + PADDING + sprite.getHeight();
		}
		// maximum scroll that can be done

		scrollMaxY = spriteY - CAMERA_HEIGHT;
		Log.d("SHOP_SCENE", spriteY + " " + CAMERA_HEIGHT + " " + scrollMaxY);
		
		
		// set the size of the scrollbar
		float scrollbarsize = (CAMERA_HEIGHT
				/ ((scrollMaxY + CAMERA_WIDTH) / CAMERA_WIDTH));
		scrollBar = new Rectangle(300, 120, 20, scrollbarsize, vbom);
		
		scrollBar.setColor(Color.BLACK);
		this.attachChild(scrollBar);

	}

	private void createBackground() {
		AutoParallaxBackground auto = new AutoParallaxBackground(0, 0, 0, 5);
		auto.attachParallaxEntity(new ParallaxEntity(0, new Sprite(0, 0,
				resourcesManager.shopBackground1Texture, vbom)));
		
	//	auto.attachParallaxEntity(new ParallaxEntity(-5.0f, new Sprite(0, 0,resourcesManager.shopBackground2Texture, vbom)));
		this.setBackground(auto);

	}
	private void createEncabezado() {
		 spriteEncabezado = new Sprite(0, 0,
				resourcesManager.encabezadoTexture, vbom);
			attachChild(spriteEncabezado);
	}
	private MenuScene menuChildScene;
	private final int SECTION1 = 0;

	private void createMenuChildScene() {
		menuChildScene = new MenuScene(camera);
		menuChildScene.setPosition(0, 0);
		final IMenuItem section1MenuItem = new ScaleMenuItemDecorator(
				new SpriteMenuItem(SECTION1,
						resourcesManager.shopSection1Texture, vbom), 1.2f, 1);
		menuChildScene.addMenuItem(section1MenuItem);
		menuChildScene.buildAnimations();
		menuChildScene.setBackgroundEnabled(false);
		section1MenuItem.setPosition(35, 125);
		menuChildScene.setOnMenuItemClickListener(this);

		setChildScene(menuChildScene);
	}

	public boolean onMenuItemClicked(MenuScene pMenuScene, IMenuItem pMenuItem,
			float pMenuItemLocalX, float pMenuItemLocalY) {
		switch (pMenuItem.getID()) {
		case SECTION1:
			return true;
		default:
			return false;
		}
	}

	@Override
	public void onScrollStarted(ScrollDetector pScollDetector, int pPointerID,
			float pDistanceX, float pDistanceY) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScroll(ScrollDetector pScollDetector, int pPointerID,
			float pDistanceX, float pDistanceY) {

		// Return if ends are reached
		if (((scrollCurrentY - pDistanceY) < scrollMinY)) {
			return;
		}

		if ((scrollCurrentY - pDistanceY) > scrollMaxY) {
			return;
		}

		// Center camera to the current point
		this.camera.offsetCenter(0, -pDistanceY);
		scrollCurrentY -= pDistanceY;

		// Set the scrollbar with the camera
		float tempY = camera.getCenterY() - camera.getHeight() / 2;
		// add the % part to the position
		tempY += (tempY / (scrollMaxY + camera.getHeight()))
				* camera.getHeight();
		// set the position
		scrollBar.setPosition(scrollBar.getX(), tempY);
		/*
		float centermenos = camera.getCenterY() - camera.getHeight() / 2;
System.out.println("cameracenter menos"+centermenos);

float centeralone = camera.getCenterY();
System.out.println("cameracenteralone"+centeralone);
*/
		spriteEncabezado.setPosition(0,camera.getCenterY() - camera.getHeight() /  2);

		// Because Camera can have negativ X values, so set to 0
		if (this.camera.getBoundsXMin() < 0) {
			this.camera.offsetCenter(0, 0);
			scrollCurrentY = 0;
		}

	}

	@Override
	public void onScrollFinished(ScrollDetector pScollDetector, int pPointerID,
			float pDistanceX, float pDistanceY) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onClick(ClickDetector pClickDetector, int pPointerID,
			float pSceneX, float pSceneY) {

		// Mirar si se ha hecho click en algun iteam de la tienda
		if (iItemClicked >= 1 && iItemClicked <= 5) {
			if (GameStatus.BuyItem(iItemClicked - 1)) {
				spritesNumItems[iItemClicked - 1].setText(String
						.valueOf(GameStatus.ITEMS[iItemClicked - 1]));
				// spritesNumItems[iItemClicked - 1].setWidth((float)
				// (sprite.getWidth() * 0.2));
				// spritesNumItems[iItemClicked - 1].setHeight((float)
				// (sprite.getHeight() * 0.2));
				// spritesNumItems[x].setX(sprite.getWidth() -
				// spritesNumItems[x].getWidth());
				ResourcesManager.getInstance().activity.toastOnUIThread(
						ItemsName[iItemClicked - 1], Toast.LENGTH_SHORT);

			} else {
				ResourcesManager.getInstance().activity.toastOnUIThread(
						"No se pudo comprar nada", Toast.LENGTH_SHORT);
			}
			iItemClicked = -1;
		}
	}

	@Override
	public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
		this.mClickDetector.onTouchEvent(pSceneTouchEvent);
		this.mScrollDetector.onTouchEvent(pSceneTouchEvent);

		
		return false;
	}

	@Override
	public void onHoldStarted(HoldDetector pHoldDetector, int pPointerID,
			float pHoldX, float pHoldY) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onHold(HoldDetector pHoldDetector, long pHoldTimeMilliseconds,
			int pPointerID, float pHoldX, float pHoldY) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onHoldFinished(HoldDetector pHoldDetector,
			long pHoldTimeMilliseconds, int pPointerID, float pHoldX,
			float pHoldY) {
		// TODO Auto-generated method stub

	}
	public void popup(){
		popup = new Sprite(0, 0, resourcesManager.shopPopupTexture,
				 resourcesManager.vbom){
			public boolean onAreaTouched(final TouchEvent pSceneTouchEvent,
					final float pTouchAreaLocalX,
					final float pTouchAreaLocalY) {
				popup.dispose();
				return true;
			}
		};
				attachChild(popup);
				// popup.setPosition(0, 0);
				 popup.setPosition(this);
				 /*
				 spritesDescriptionItems = new Text(50, 50,
							resourcesManager.itemsDescriptionFont, "holacomoestas", 10,
							resourcesManager.vbom);
				 spritesDescriptionItems.setText("holacomoestas");
				*/
	}

}
